import { request } from '@/utils/request'
import type { ApiResponse, PaginatedResponse } from '@/types/api'

// 测试用例接口
export interface TestCase {
  id: string
  title: string
  description?: string
  preconditions?: string
  test_steps: TestCaseStep[]
  expected_result?: string
  postconditions?: string
  type: TestCaseType
  category: TestCaseCategory
  status: TestCaseStatus
  priority: TestCasePriority | 'medium'
  project_id?: string
  project_name?: string
  requirement_id?: string
  requirement_name?: string
  task_id?: string
  task_name?: string
  defect_id?: string
  defect_name?: string
  folder_id?: string
  assignee_id?: string
  assignee_name?: string
  creator_id?: string
  creator_name?: string
  tags: string[]
  estimated_duration?: number
  automation_status?: string
  automation_script_path?: string
  organization_id?: string
  execution_count: number
  last_execution_date?: string
  last_execution_result?: ExecutionResult
  pass_rate?: number
  comments: TestCaseComment[]
  attachments: TestCaseAttachment[]
  created_by: string
  created_at: string
  updated_at: string
  comment_count: number
  attachment_count: number
}

export interface TestCaseStep {
  step_number: number
  action: string
  expected_result: string
  actual_result?: string
  execution_result?: ExecutionResult
  attachments?: string[]
  notes?: string
}

export interface TestCaseComment {
  id: string
  content: string
  author_id: string
  author_name?: string
  author_avatar?: string
  parent_comment_id?: string | null
  is_deleted?: boolean
  created_at: string
  updated_at?: string
}

export interface TestCaseAttachment {
  id: string
  filename: string
  file_path: string
  file_size: number
  content_type: string
  uploaded_by: string
  uploaded_at: string
}

export type TestCaseStatus = 'design' | 'ready' | 'executing' | 'passed' | 'failed' | 'blocked' | 'skipped' | 'deprecated'
export type TestCasePriority = 'lowest' | 'low' | 'medium' | 'high' | 'urgent' | 'critical' | 'blocker'
export type TestCaseType = 'functional' | 'integration' | 'system' | 'regression' | 'smoke' | 'performance' | 'security' | 'usability' | 'compatibility' | 'ui' | 'api' | 'e2e'
export type TestCaseCategory = 'positive' | 'negative' | 'boundary' | 'edge' | 'error_handling' | 'security' | 'performance'
export type ExecutionResult = 'passed' | 'failed' | 'blocked' | 'skipped' | 'not_run'

export interface TestCaseCreate {
  title: string
  description?: string
  preconditions?: string
  test_steps?: TestCaseStep[]
  expected_result?: string
  postconditions?: string
  type?: TestCaseType
  category?: TestCaseCategory
  status?: TestCaseStatus
  priority?: TestCasePriority
  project_id?: string
  requirement_id?: string
  task_id?: string
  defect_id?: string
  folder_id?: string
  assignee_id?: string
  creator_id?: string
  tags?: string[]
  estimated_duration?: number
  automation_status?: string
  automation_script_path?: string
}

export interface TestCaseUpdate {
  title?: string
  description?: string
  preconditions?: string
  test_steps?: TestCaseStep[]
  expected_result?: string
  postconditions?: string
  type?: TestCaseType
  category?: TestCaseCategory
  status?: TestCaseStatus
  priority?: TestCasePriority
  project_id?: string
  requirement_id?: string
  task_id?: string
  defect_id?: string
  folder_id?: string
  assignee_id?: string
  tags?: string[]
  estimated_duration?: number
  automation_status?: string
  automation_script_path?: string
}

export interface TestCaseFilter {
  search?: string
  project_id?: string
  requirement_id?: string
  task_id?: string
  defect_id?: string
  folder_id?: string
  assignee_id?: string
  creator_id?: string
  status?: TestCaseStatus
  priority?: TestCasePriority
  test_case_type?: TestCaseType
  category?: TestCaseCategory
  automation_status?: string
  tags?: string[]
  created_start?: string
  created_end?: string
  updated_start?: string
  updated_end?: string
  page?: number
  size?: number
  sort_by?: string
  sort_order?: 'asc' | 'desc'
  skip?: number
  limit?: number
}

export interface TestCaseStats {
  total_test_cases: number
  test_cases_by_status: Record<string, number>
  test_cases_by_type: Record<string, number>
  test_cases_by_priority: Record<string, number>
  test_cases_by_category: Record<string, number>
  execution_stats: Record<string, number>
  pass_rate?: number
}

export interface TestCaseExecution {
  id: string
  test_case_id: string
  test_case_title?: string
  execution_result: ExecutionResult
  executed_by: string
  executed_by_name?: string
  execution_date: string
  execution_environment?: string
  step_results: any[]
  actual_result?: string
  failure_reason?: string
  blocker_reason?: string
  duration?: number
  attachments: string[]
  notes?: string
  defect_id?: string
  project_id?: string
  test_plan_id?: string
  test_run_id?: string
  created_at: string
  updated_at: string
}

// VersionTestReport已移除，请使用TestReport接口（在test-report.ts中定义）

export interface TestCaseExecutionCreate {
  test_case_id: string
  execution_result: ExecutionResult
  executed_by: string
  execution_date?: string
  execution_environment?: string
  step_results?: any[]
  actual_result?: string
  failure_reason?: string
  blocker_reason?: string
  duration?: number
  attachments?: string[]
  notes?: string
  defect_id?: string
  project_id?: string
  test_plan_id?: string
  test_run_id?: string
}

// API 函数
export const getTestCases = async (params?: TestCaseFilter): Promise<{
  items: TestCase[]
  total: number
  page: number
  size: number
}> => {
  // 转换参数：将 page/size 转换为 skip/limit
  const requestParams: any = {}
  if (params) {
    const page = params.page || 1
    const size = params.size || 20
    requestParams.skip = (page - 1) * size
    requestParams.limit = size
    
    // 复制其他参数
    if (params.search) requestParams.search = params.search
    if (params.project_id) requestParams.project_id = params.project_id
    if (params.requirement_id) requestParams.requirement_id = params.requirement_id
    if (params.task_id) requestParams.task_id = params.task_id
    if (params.defect_id) requestParams.defect_id = params.defect_id
    if (params.folder_id) requestParams.folder_id = params.folder_id
    if (params.assignee_id) requestParams.assignee_id = params.assignee_id
    if (params.creator_id) requestParams.creator_id = params.creator_id
    if (params.status) requestParams.status = params.status
    if (params.priority) requestParams.priority = params.priority
    if (params.test_case_type) requestParams.test_case_type = params.test_case_type
    if (params.category) requestParams.category = params.category
    if (params.automation_status) requestParams.automation_status = params.automation_status
    if (params.tags && params.tags.length > 0) requestParams.tags = params.tags.join(',')
    if (params.created_start) requestParams.created_start = params.created_start
    if (params.created_end) requestParams.created_end = params.created_end
    if (params.updated_start) requestParams.updated_start = params.updated_start
    if (params.updated_end) requestParams.updated_end = params.updated_end
    if (params.sort_by) requestParams.sort_by = params.sort_by
    if (params.sort_order) requestParams.sort_order = params.sort_order
  }
  
  const response = await request.get('/test-cases/', { params: requestParams })
  
  // 处理后端统一响应格式
  // 后端paginated_response返回格式：{success: true, data: [...], pagination: {...}}
  if (response.data && response.data.success) {
    const data = response.data.data
    const pagination = response.data.pagination // pagination在响应数据的顶级
    
    // 后端返回的是数组格式，pagination是顶级字段
    if (Array.isArray(data) && pagination) {
      return {
        items: data.map((testCase: any) => ({
          ...testCase,
          id: testCase.id || testCase._id,
          assignee_name: testCase.assignee_name || testCase.assignee?.name || testCase.assignee?.username,
          creator_name: testCase.creator_name || testCase.creator?.name || testCase.creator?.username,
          project_name: testCase.project_name || testCase.project?.name,
          requirement_name: testCase.requirement_name || testCase.requirement?.title,
          status: testCase.status || '',
          priority: testCase.priority || 'medium'
        })),
        total: pagination.total || 0,
        page: pagination.page || 1,
        size: pagination.size || (params?.size || 20)
      }
    }
  }
  
  // 如果响应格式不符合预期，返回空数组并记录警告
  console.warn('Unexpected test case list response format:', response.data)
  return {
    items: [],
    total: 0,
    page: params?.page || 1,
    size: params?.size || 20
  }
}

export const getTestCaseById = async (id: string): Promise<ApiResponse<TestCase>> => {
  const response = await request.get(`/test-cases/${id}`)
  if (response.data.success === false) {
    throw new Error(response.data.message || 'Failed to get test case')
  }
  return response.data
}

export const createTestCase = async (data: TestCaseCreate): Promise<ApiResponse<TestCase>> => {
  const response = await request.post('/test-cases/', data)
  if (response.data.success === false) {
    throw new Error(response.data.message || 'Failed to create test case')
  }
  return response.data
}

export const updateTestCase = async (id: string, data: TestCaseUpdate): Promise<ApiResponse<TestCase>> => {
  const response = await request.put(`/test-cases/${id}`, data)
  if (response.data.success === false) {
    throw new Error(response.data.message || 'Failed to update test case')
  }
  return response.data
}

export const deleteTestCase = async (id: string): Promise<ApiResponse<null>> => {
  const response = await request.delete(`/test-cases/${id}`)
  if (response.data.success === false) {
    throw new Error(response.data.message || 'Failed to delete test case')
  }
  return response.data
}

export const updateTestCaseStatus = async (id: string, status: TestCaseStatus): Promise<ApiResponse<TestCase>> => {
  const response = await request.patch(`/test-cases/${id}/status`, { status })
  if (response.data.success === false) {
    throw new Error(response.data.message || 'Failed to update test case status')
  }
  return response.data
}

export const updateTestCaseAssignee = async (id: string, assignee_id?: string): Promise<ApiResponse<TestCase>> => {
  const response = await request.patch(`/test-cases/${id}/assignee`, { assignee_id })
  if (response.data.success === false) {
    throw new Error(response.data.message || 'Failed to update test case assignee')
  }
  return response.data
}

export const getTestCaseExecutions = async (
  testCaseId: string,
  params?: { skip?: number; limit?: number }
): Promise<{
  items: TestCaseExecution[]
  total: number
  page: number
  size: number
}> => {
  const response = await request.get(`/test-cases/${testCaseId}/executions`, { params })
  
  if (response.data && response.data.success) {
    const data = response.data.data
    const pagination = response.data.pagination
    
    if (Array.isArray(data) && pagination) {
      return {
        items: data,
        total: pagination.total || 0,
        page: pagination.page || 1,
        size: pagination.size || (params?.limit || 20)
      }
    }
    
    if (data && typeof data === 'object' && data.items && Array.isArray(data.items)) {
      return {
        items: data.items,
        total: data.total || data.pagination?.total || 0,
        page: data.page || data.pagination?.page || 1,
        size: data.size || data.pagination?.size || (params?.limit || 20)
      }
    }
  }
  
  return {
    items: [],
    total: 0,
    page: params?.skip ? Math.floor(params.skip / (params.limit || 20)) + 1 : 1,
    size: params?.limit || 20
  }
}

export const createTestCaseExecution = async (
  testCaseId: string,
  data: TestCaseExecutionCreate
): Promise<ApiResponse<TestCaseExecution>> => {
  const response = await request.post(`/test-cases/${testCaseId}/executions`, data)
  if (response.data.success === false) {
    throw new Error(response.data.message || 'Failed to create test case execution')
  }
  return response.data
}

export const getTestCaseStats = async (params?: {
  project_id?: string
}): Promise<ApiResponse<TestCaseStats>> => {
  const response = await request.get('/test-cases/stats/summary', { params })
  if (response.data.success === false) {
    throw new Error(response.data.message || 'Failed to get test case stats')
  }
  return response.data
}

export const getTestCasesByProject = async (
  projectId: string,
  params?: TestCaseFilter
): Promise<PaginatedResponse<TestCase>> => {
  const response = await request.get('/test-cases/', {
    params: {
      ...params,
      project_id: projectId
    }
  })
  if (response.data.success === false) {
    throw new Error(response.data.message || 'Failed to get test cases by project')
  }
  return response.data
}

// 测试用例文件夹 API
export interface TestCaseFolder {
  id: string
  name: string
  description?: string
  project_id: string
  parent_id?: string
  creator_id: string
  sort_order: number
  test_case_count: number
  created_at: string
  updated_at: string
  children?: TestCaseFolder[]
}

export interface TestCaseFolderCreate {
  name: string
  description?: string
  project_id: string
  parent_id?: string
  sort_order?: number
}

export interface TestCaseFolderUpdate {
  name?: string
  description?: string
  project_id?: string
  parent_id?: string
  sort_order?: number
}

export const getTestCaseFolders = async (params?: {
  project_id?: string
  tree?: boolean
}): Promise<ApiResponse<TestCaseFolder[]>> => {
  const response = await request.get('/test-cases/folders', { params })
  if (response.data.success === false) {
    throw new Error(response.data.message || 'Failed to get test case folders')
  }
  return response.data
}

export const getTestCaseFolderById = async (id: string): Promise<ApiResponse<TestCaseFolder>> => {
  const response = await request.get(`/test-cases/folders/${id}`)
  if (response.data.success === false) {
    throw new Error(response.data.message || 'Failed to get test case folder')
  }
  return response.data
}

export const createTestCaseFolder = async (data: TestCaseFolderCreate): Promise<ApiResponse<TestCaseFolder>> => {
  const response = await request.post('/test-cases/folders', data)
  if (response.data.success === false) {
    throw new Error(response.data.message || 'Failed to create test case folder')
  }
  return response.data
}

export const updateTestCaseFolder = async (id: string, data: TestCaseFolderUpdate): Promise<ApiResponse<TestCaseFolder>> => {
  const response = await request.put(`/test-cases/folders/${id}`, data)
  if (response.data.success === false) {
    throw new Error(response.data.message || 'Failed to update test case folder')
  }
  return response.data
}

export const deleteTestCaseFolder = async (id: string): Promise<ApiResponse<null>> => {
  const response = await request.delete(`/test-cases/folders/${id}`)
  if (response.data.success === false) {
    throw new Error(response.data.message || 'Failed to delete test case folder')
  }
  return response.data
}

// 测试用例评论API
export const getTestCaseComments = async (
  testCaseId: string,
  page: number = 1,
  pageSize: number = 20
): Promise<ApiResponse<{ items: TestCaseComment[], total: number, page: number, page_size: number }>> => {
  const response = await request.get(`/comments/test_case/${testCaseId}/comments`, {
    params: { page, page_size: pageSize }
  })
  if (response.data.success === false) {
    throw new Error(response.data.message || 'Failed to get test case comments')
  }
  return response.data
}

export const addTestCaseComment = async (
  testCaseId: string,
  content: string,
  parentCommentId?: string | null
): Promise<ApiResponse<TestCaseComment>> => {
  const response = await request.post(`/comments/test_case/${testCaseId}/comments`, {
    content,
    parent_comment_id: parentCommentId
  })
  if (response.data.success === false) {
    throw new Error(response.data.message || 'Failed to add test case comment')
  }
  return response.data
}

export const updateTestCaseComment = async (
  testCaseId: string,
  commentId: string,
  data: { content?: string; is_deleted?: boolean }
): Promise<ApiResponse<TestCaseComment>> => {
  const response = await request.put(`/comments/test_case/${testCaseId}/comments/${commentId}`, data)
  if (response.data.success === false) {
    throw new Error(response.data.message || 'Failed to update test case comment')
  }
  return response.data
}

export const deleteTestCaseComment = async (
  testCaseId: string,
  commentId: string
): Promise<ApiResponse<null>> => {
  const response = await request.put(`/comments/test_case/${testCaseId}/comments/${commentId}`, { is_deleted: true })
  if (response.data.success === false) {
    throw new Error(response.data.message || 'Failed to delete test case comment')
  }
  return response.data
}

// 导出testCaseAPI对象以兼容其他文件的导入
export const testCaseAPI = {
  getTestCases,
  getTestCaseById,
  createTestCase,
  updateTestCase,
  deleteTestCase,
  updateTestCaseStatus,
  updateTestCaseAssignee,
  getTestCaseExecutions,
  createTestCaseExecution,
  getTestCaseStats,
  getTestCasesByProject,
  getTestCaseFolders,
  getTestCaseFolderById,
  createTestCaseFolder,
  updateTestCaseFolder,
  deleteTestCaseFolder,
  getTestCaseComments,
  addTestCaseComment,
  updateTestCaseComment,
  deleteTestCaseComment
}

